package com.anbao.server;

import com.anbao.util.CommonData;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;

public class SeocketServer extends Service {

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		// 注册广播
		registerBoradcastReceiver();
		//将服务对象传给socket客户端
		SoketClient.getSoketClient().setSeocketServer(this);

	}

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			
			
			
			if (action.equals(CommonData.LOGINACTION)) {
				
				byte[] data = intent.getExtras().getByteArray("data");
				SoketClient.getSoketClient().sendMessage(data);

			} else if (action.equals(CommonData.SHEFANGACTION)) {

				byte[] data = intent.getExtras().getByteArray("data");
				SoketClient.getSoketClient().sendMessage(data);

			} else if (action.equals(CommonData.CHEFANGACTION)) {

				byte[] data = intent.getExtras().getByteArray("data");
				SoketClient.getSoketClient().sendMessage(data);
				
			} else if (action.equals(CommonData.UPDATEPWDACTION)) {
				
				byte[] data = intent.getExtras().getByteArray("data");
				SoketClient.getSoketClient().sendMessage(data);
				
			}else if (action.equals(CommonData.CONNECTSCOKETACTION)) {
				
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						// 连接socket
						SoketClient.getSoketClient().connectServer(CommonData.sockeIp,CommonData.socketPort);	
						//将socket连接的结果发送给欢迎界面
						 Intent mIntent = new Intent(CommonData.CONNECTSCOKETACTIONRESULT);  
				         mIntent.putExtra("data", SoketClient.getSoketClient().getRunState());  
				            //发送广播  
				         SeocketServer.this.sendBroadcast(mIntent); 
						
					}
				}).start();
				
			}
		}

	};

	public void registerBoradcastReceiver() {
		IntentFilter myIntentFilter = new IntentFilter();
		// 注册登录广播
		myIntentFilter.addAction(CommonData.LOGINACTION);
		// 注册设防广播
		myIntentFilter.addAction(CommonData.SHEFANGACTION);
		// 注册撤防广播
		myIntentFilter.addAction(CommonData.CHEFANGACTION);
		// 注册修改密码广播
		myIntentFilter.addAction(CommonData.UPDATEPWDACTION);
//		 注册修改密码广播
		myIntentFilter.addAction(CommonData.CONNECTSCOKETACTION);
		// 注册广播
		registerReceiver(mBroadcastReceiver, myIntentFilter);
	}

}
